package com.ruoyi.web.controller;

import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.Comment;
import com.ruoyi.web.domain.MyMessage;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.ICommentService;
import com.ruoyi.web.utils.UserMsgUtil;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IMyMessageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * messageController
 *
 * @author ruoyi
 * @date 2024-04-24
 */
@RestController
@RequestMapping("/wx/message")
public class MyMessageController extends BaseController {
    @Autowired
    private IMyMessageService myMessageService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private FileService fileService;

    /**
     * 查询message列表
     */
    @PostMapping("/list")
    public AjaxResult list(@RequestBody MyMessage myMessage) {
        System.err.println(myMessage);
//        startPage();
        if (UserMsgUtil.getUserId() != null) {
            // 当前用户存在
            myMessage.setUserId(UserMsgUtil.getUserId());
        }
        List<MyMessage> list = myMessageService.selectMyMessageList(myMessage);
        System.err.println(list);
        // 赋值avatar、username、content
        list = list.stream().peek(item -> {
            if (item.getComment() != null) {
                // 评论消息
                Comment comment = item.getComment();
                if (comment.getAvatar() != null) {
                    String avatar = UserMsgUtil.subAvatar(comment.getAvatar());
                    item.setAvatar(avatar);// avatar
                }
                item.setUsername(comment.getUsername());// username
                item.setContent(comment.getContent());// content
            } else if (item.getSysUser() != null) {
                // 好友申请
                SysUser sysUser = item.getSysUser();
                if (sysUser.getAvatar() != null) {
                    String avatar = UserMsgUtil.subAvatar(sysUser.getAvatar());
                    item.setAvatar(avatar);// avatar
                }
                item.setUsername(sysUser.getUserName());// username
            }
        }).collect(Collectors.toList());

//        return getDataTable(list);
        return AjaxResult.success(list);
    }


    /**
     * 导出message列表
     */
    @Log(title = "message", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MyMessage myMessage) {
        List<MyMessage> list = myMessageService.selectMyMessageList(myMessage);
        ExcelUtil<MyMessage> util = new ExcelUtil<MyMessage>(MyMessage.class);
        util.exportExcel(response, list, "message数据");
    }

    /**
     * 获取message详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(myMessageService.selectMyMessageById(id));
    }

    /**
     * 新增message
     */
    @Log(title = "message", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyMessage myMessage) {
        // 手动赋值：username、avatar、content
        // 若为好友请求，username、avatar为发送者user的、content=null
        // 若为评论，username、avatar、content为comment里的
        if (myMessage.getMsgType() == 0l) {
            // 消息为好友请求
            if (UserMsgUtil.getUserId() != null) {
                // 当前用户存在
                SysUser sysUser = userService.selectUserById(UserMsgUtil.getUserId());
                // 此处friendId是发送好友请求的本用户
                myMessage.setFriendId(sysUser.getUserId());
                myMessage.setContent("你好，我是" + sysUser.getUserName());
                return toAjax(myMessageService.insertMyMessage(myMessage));
            }
            return AjaxResult.error("添加信息失败");
        } else if (myMessage.getMsgType() == 1l) {
            // 消息为添加评论消息
            // 先将信息添加到comment中，再添加到msg中
            Comment comment = new Comment();
            comment.setPostId(myMessage.getPostId());
            comment.setContent(myMessage.getContent());
            comment.setTime(myMessage.getTime());
            int row = commentService.insertComment(comment);
            if (row > 0) {
                // comment插入成功
                myMessage.setCommentId((long) row);
                // 设置friendId(发送者)
                if (UserMsgUtil.getUserId() != null) {
                    // 当前用户存在
                    SysUser sysUser = userService.selectUserById(UserMsgUtil.getUserId());
                    // 此处friendId是发送评论的本用户
                    myMessage.setFriendId(sysUser.getUserId());
                }
                return toAjax(myMessageService.insertMyMessage(myMessage));
            }
            return AjaxResult.success("插入comment失败");
        }
        return AjaxResult.success("msgType信息有误");
    }

    /**
     * 修改message
     */
    @Log(title = "message", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyMessage myMessage) {
        return toAjax(myMessageService.updateMyMessage(myMessage));
    }

    /**
     * 删除message
     */
    @Log(title = "message", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(myMessageService.deleteMyMessageByIds(ids));
    }
}
